package com.example.anew.journey.mynewjourney.logic.login.persenter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.anew.journey.mynewjourney.base.MyApplication;
import com.example.anew.journey.mynewjourney.config.RBConstants;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeMain.FirstChangeMainActivity;
import com.example.anew.journey.mynewjourney.logic.login.bean.LoginBean;
import com.example.anew.journey.mynewjourney.logic.login.model.ISLoginModel;
import com.example.anew.journey.mynewjourney.logic.login.model.LoginModel;
import com.example.anew.journey.mynewjourney.logic.login.view.ISLoginView;
import com.example.anew.journey.mynewjourney.logic.thirdPartyLogin.ThirdPartyLoginActivity;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.HashMap;

import cn.jesse.nativelogger.NLogger;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司09
 * Created by 20433 on 2018/3/23
 *
 * @desc 东风山河绿，春已不折柳，繁花看不尽，处处惹人留
 * @desc 佛祖镇楼，bug辟容易
 */

public class LoginPersenter {
    private ISLoginView mISSetPasswordView;
    private ISLoginModel mISLoginModel ;
    public LoginPersenter(ISLoginView iSSetPasswordView) {
        this.mISSetPasswordView = iSSetPasswordView;
        mISLoginModel = new LoginModel();
    }

    //点击登陆
    public void onClickLogin(Context mContext) {
        String phoneNumber = mISSetPasswordView.getPhoneNumber();
        String password = mISSetPasswordView.getPassword();
        if (TextUtils.isEmpty(phoneNumber) || phoneNumber == null ) {
           // mISSetPasswordView.showToastInformation("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            mISSetPasswordView.showToastInformation("请输入密码");
            return;
        }
        mISSetPasswordView.displayProgress();
        submit(phoneNumber, password,mContext);
    }

    private void submit(String phoneNumber, String password, final Context mContext) {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL + RBConstants.LOGIN)
                .addParams("tel", phoneNumber)
                .addParams("password", password)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        final LoginBean loginBean = gson.fromJson(NetworkResponseDate, LoginBean.class);
                        // TODO 移植
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if (loginBean.errorCode == 200){
                                    mISSetPasswordView.toFirstChangeMainActivity();
                                    LoginBean.DataBean bean = loginBean.data;
                                    if(bean != null)
                                        mISLoginModel.storeData(bean,mContext);
                                }else{
                                    mISSetPasswordView.showToastInformation(loginBean.errorMessage);
                                }
                                mISSetPasswordView.hiddenProgress();
                            }
                        });
                        return null;
                    }
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                mISSetPasswordView.hiddenProgress();
                                mISSetPasswordView.showToastInformation("请查看网络");
                            }
                        });

                    }
                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    //点击免密码登陆
    public void onClickPasswordFreeLogin() {
        mISSetPasswordView.toPasswordFreeLogin();
    }

    // 点击忘记密码
    public void onClickForgotPassword() {
        mISSetPasswordView.toForgotPassword();
    }

    //点击微信登陆
    public void onClickWecht(final Context mContext) {
        Platform Wachzone = ShareSDK.getPlatform(Wechat.NAME);
        if(Wachzone.isAuthValid()) {
            Wachzone.removeAccount(true);
        }
        Wachzone.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                arg0.getDb().exportData();
                //Toast.makeText(SharedSdkActivity.this, "成功", Toast.LENGTH_SHORT).show();
                //获取资料
                String UserName = arg0.getDb().getUserName();//获取用户名字
                String Icon = arg0.getDb().getUserIcon(); //获取用户头像
                String token = arg0.getDb().getToken();
                String userId =  arg0.getDb().getUserId();
               LoginWecht("weixin",userId,mContext);

            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "登录取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
//authorize与showUser单独调用一个即可
        Wachzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    }

    private void LoginWecht(final String weixin, final String userId, final Context mContext) {
        String url = RBConstants.SERVER_URL+RBConstants.THIRD_PARTY_LOGIN;
        OkHttpUtils
                .post()
                .url(url)
                .addParams(weixin,userId)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                       NLogger.e("TAG","=====23====LoginWecht============"+NetworkResponseDate);
                        final LoginBean bean =  gson.fromJson(NetworkResponseDate, LoginBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(bean.errorCode == 200){
                                    mISSetPasswordView.toFirstChangeMainActivity();
                                    LoginBean.DataBean mbean = bean.data;
                                    //todo 存储
                                    if(mbean != null) {
                                        mISLoginModel.storeData(mbean,mContext);
                                        Intent intent_01 = new Intent(mContext, FirstChangeMainActivity.class);
                                        mContext.startActivity(intent_01);
                                        mISSetPasswordView.showToastInformation("登录成功");
                                    }
                                }else if(bean.errorCode == 4001){  //未绑定手机号
                                    Intent intent = new Intent(mContext,ThirdPartyLoginActivity.class);
                                    intent.putExtra("third_party_login_state","1");  //Third party login
                                    intent.putExtra("third_party_login_id",userId);  //Third party login
                                    intent.putExtra("third_party_login_name",weixin);  //Third party login
                                    mContext.startActivity(intent);
                                    mISSetPasswordView.showToastInformation("未绑定手机号，请注册手机号");
                                }else{
                                    mISSetPasswordView.showToastInformation(bean.errorMessage);
                                }
                            }
                        });


                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                       // NLogger.e("TAG","=====23====LoginWecht==123=========="+e);
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    // 点击qq登陆
    public void onClickQQ(final Context mContext) {
        Platform qzone = ShareSDK.getPlatform(QQ.NAME);
        if(qzone.isAuthValid()) {
            qzone.removeAccount(true);
        }
        qzone.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                arg0.getDb().exportData();
                //获取资料
                String UserName = arg0.getDb().getUserName();//获取用户名字
                String Icon = arg0.getDb().getUserIcon(); //获取用户头像
                String token = arg0.getDb().getToken();
                String userID =  arg0.getDb().getUserId();
                LoginWecht("qq",userID,mContext);
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "登录取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        qzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    }

}
